import axios from 'axios';
import { Message } from 'element-ui';
import store from '../store/index.js';
import router from '../router'; // 确保你已经引入了路由

let _axios = axios.create({
    baseURL: 'http://1.94.210.234:8080/api',
});

// 请求拦截器
_axios.interceptors.request.use(
    async function (config) {
        let authorization = localStorage.getItem('list');
        if (authorization) {
            let token = JSON.parse(authorization);
            if (token.expire < Date.now()) {
                localStorage.removeItem('list');
                Message({
                    message: '登录过期请重新登录',
                    type: 'warning'
                });
                router.push("/login");
            }
            config.headers = {
                ...config.headers,
                Authorization: 'Bearer ' + token.token
            };
        }
        return config;
    },
    function (error) {
        return Promise.reject(error);
    }
);

// 响应拦截器
_axios.interceptors.response.use(
    function (response) {
        let authorization = localStorage.getItem('list');
        if (response.data.code === 400) {
            Message({
                message: '警告哦，这是一条警告消息',
                type: 'warning'
            });
        } else if (response.data.code === 403) {
            Message({
                message: '警告哦，这是一条警告消息',
                type: 'warning'
            });
        } else if (response.data.code === 404) {
            Message({
                message: '警告哦，这是一条警告消息',
                type: 'warning'
            });
        } else if (response.data.code === 401 && authorization !== null) {
            Message({
                message: '账号在别的地方登录，请重新登录',
                type: 'warning',
                duration: 500,
                onClose: () => {
                    localStorage.removeItem('list');
                    router.push('/login')
                    location.reload()
                }
            });
        }else if(response.data.code === 401){
            Message({
                message: '请登录后操作',
                type: 'warning',
                duration: 700,
                onClose: () => {
                    router.push('/login')
                    location.reload()
                }
            });
        }
        return response;
    },
    function (error) {
        return Promise.reject(error);
    }
);

export default _axios;